<?php

namespace App\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // 非 local 环境统一转为 https
        $this->app['request']->server->set('HTTPS', !isLocal());
        // 添加手机号验证规则
        Validator::extend('phone', function ($attribute, $value, $parameters, $validator) {
            return preg_match("/^1[23456789]\d{9}$/", $value);
        });
        // 验证手机号列表
        Validator::extend('phoneList', function ($attribute, $value, $parameters, $validator) {
            $phoneList = explode(',', $value);
            foreach ($phoneList as $phone) {
                if (!preg_match("/^1[23456789]\d{9}$/", $phone)) {
                    return false;
                }
            }
            return true;
        });
        // 添加密码验证规则
        Validator::extend('pattern_password', function ($attribute, $value, $parameters, $validator) {
            return preg_match("/^(?=.*\d)(?=.*[a-zA-Z]).{8,16}$/", $value);
        });
        // 添加链接验证规则
        Validator::extend('pattern_domain', function ($attribute, $value, $parameters, $validator) {
            return preg_match("((\w+):\/\/([^/:]+)\/)", $value);
        });
        // 添加邮箱验证规则
        Validator::extend('pattern_email', function ($attribute, $value, $parameters, $validator) {
            return preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $value);
        });
        // 记录SQL日志
        DB::listen(function ($sql) {
            if (strpos($sql->sql, 'from "nice_jobs"')) {
                return false;
            }
            foreach ($sql->bindings as $i => $binding) {
                if ($binding instanceof \DateTime) {
                    $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                } else {
                    if (is_string($binding)) {
                        $sql->bindings[$i] = "'$binding'";
                    }
                }
            }
            // Insert bindings into query
            $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
            $query = vsprintf($query, $sql->bindings);
            // Save the query to file
            Log::info("[SQL] " . $query . ";" . PHP_EOL);
            return true;
        });

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment() !== 'prod') {
            $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
        }
    }
}
